<template>
	<view class="_abbr">
		<view class="public">
			<view class="detail">
				<view class="main_body_view main_body_view_title">
					<u-row>
						{{dataForm.workOrderId}}
					</u-row>
				</view>
				<view class="main_body_view">
					指派人：{{dataForm.dispUserName}}</u-col>
				</view>
				<view class="main_body_view">
					时间：{{dataForm.preStartTime|formatDate('MM-dd HH:mm')}}
				</view>
				<view class="main_body_view">
					被指派人：{{dataForm.supUserName}}
				</view>
				<view class="main_body_view">内容：{{dataForm.workOrderContent}}</view>
				<text class="main_body_view">备注：{{dataForm.remark||''}}</text>
			</view>
		</view>
		<view class="public">
			<view>现场照片</view>
			<view>
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :deletable="proud==14"
					 multiple :maxCount="10">
				</u-upload>
			</view>
		</view>
		<view class="public">
			<view class="title">派发附件</view>
			<view v-for="(item, index) in fileAttachments" :key="index">
				<u-row gutter="12">
					<u-col span="10" textAlign="center" align="center">
						<view class="file">{{item.mediaName}}</view>
					</u-col>
					<u-col span="2" textAlign="center" align="center">
						<u-button size="medium" @click="previewFile(item)" type="primary" plain>预览</u-button>
						<!-- <u-button size="medium" @click="downLoad(item)">预览</u-button> -->
					</u-col>
				</u-row>
			</view>
		</view>
		<view class="public">
			<view>派单照片</view>
			<view v-for="(item, index) in fileImage" :key="item.mediaId">
				 <image mode="widthFix" :src="item.fileUrl" style="width: 40%;"></image>
			</view>
		</view>
		<view class="public">
			<view class="sub">
				<u-button type="primary" @click="sub" text="提交" :disabled="buttonDisabled"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	export default {
		name: 'main',
		onLoad(options) {
			uni.showLoading({
				title: "正在加载中"
			})
			this.getData(options.workId);
			this.BaseUrl = getApp().globalData.baseURL;
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				show: false,
				buttonDisabled: false,
				proud: "",
				BaseUrl: "",
				dataForm: {}, // 数据工单
				subForm: {
					workOrderId: null,
					method: "all_end"
				}, //提交工单
				WorkOrderMediaBo: [], //工单文件
				nowImages: { //现场照片
					workOrderId: '',
					mediaType: "1005",
					mediaName: '现场照片',
					fileUrls: []
				},
				fileList1: [], //现场照片
				fileList2: [],
				writeFlag: undefined,
				fileImage: [], //派单照片
				fileAttachments: [], // 派单附件
				schedule: 0,
			}
		},
		methods: {
			sub() {
				this.nowImages.workOrderId = this.dataForm.workOrderId
				request({
					url: 'system/orderMedia',
					method: 'POST',
					data: this.nowImages
				})
				request({
					url: 'system/orderTemp',
					method: "PUT",
					data: this.subForm
				}).then(res => {
					console.log('提交', res)
					uni.reLaunch({
						url: '/pages/view/temporary/index'
					})
				})
			},
			// 预览excel
			previewFile(item) {
				uni.showLoading({
					title: '正在打开...'
				});
				this.schedule = 0; //载入进度为0

				const downloadTask = uni.downloadFile({
					url: item.fileUrl, // 图片或者文件地址
					success: function(res) {
						// console.log('下载的res', res);
						var filePath = res.tempFilePath; // 临时文件存储路径
						//  文件打开文件预览
						uni.openDocument({
							filePath: encodeURI(filePath),
							// fileType: 'pdf',
							success: function(res) {
								uni.hideLoading();
								// console.log('打开文档成功');
							},
							fail: function(err) {
								uni.hideLoading();
								uni.showToast({
									title: '打开失败',
									duration: 1500,
									icon: 'none'
								});
								console.log('打开失败');
							}
						});
					},
					fail: function(err) {
						console.log('下载失败原因', err);
						uni.hideLoading();
						uni.showModal({
							title: '您需要授权相册权限',
							success(res) {
								if (res.confirm) {
									uni.openSetting({
										success(res) {},
										fail(res) {
											console.log(res);
										}
									});
								}
							}
						});
					}
				});
				downloadTask.onProgressUpdate(res => {
					// console.log('下载进度' + res.progress);
					this.schedule = res.progress
				});
			},
			// 下载附件
			downLoad(item){
				console.log(item.fileUrl)
				// url是文件路径，这个需要自己取。一般是后台传过来的
				let url = item.fileUrl
				uni.showActionSheet({
				  itemList: ["保存文件到本地"],
				  success:(res)=> {
					if (res.tapIndex == 0) {
					  uni.showLoading({
						title: "保存中..."
					  })
					  uni.downloadFile({
						url:url,
						success:(result)=> {
						  var tempFilePath = result.tempFilePath;
						  //这个地方开始分开表格和图片。检索到有'xlsx'字符串为表格。否则为图片
						  if(url.indexOf('xlsx')>0){
							console.log('表格')
							uni.openDocument({
								filePath: tempFilePath,
								success:()=> {
									uni.showToast({
									title: "保存成功",
									duration: 2000
									})
								},
								fail:()=>{
									console.log("openDocument 失败");
									uni.hideLoading();
								},
								complete: function() {
									uni.hideLoading();
								}
							})
						  }else{
							console.log('图片')
							uni.saveImageToPhotosAlbum({
								filePath: tempFilePath,
								success:()=> {
									uni.showToast({
										title: "保存成功",
										duration: 2000
									})
								},
								fail:()=>{
									console.log("saveImageToPhotosAlbum 失败");
									uni.hideLoading();
								},
								complete: function() {
									uni.hideLoading();
								}
							})
						  }
						},
						fail:()=> {
							console.log("downloadFile 失败");
						}
					  })
					}
				  },
				  fail:()=> {
					console.log("showActionSheet 失败");
				  }
				})
			},

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				console.log(lists);
				console.log(this.BaseUrl);
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						console.log("upload", res);
						if (name == 1) {
							this.nowImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						} 
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			// 请求数据
			getData(workId) {
				console.log('workId', workId);
				request({
					method: "GET",
					url: `system/orderTemp/${workId}`
				}).then(res => {
					console.log('响应：', res);
					this.dataForm = res.data;
					this.subForm.workOrderId = res.data.workOrderId;
					this.proud = res.data.workOrderStatusId - 0;
					this.fileImage = res.data.workOrderMediaVos.filter(item => item.mediaType === "1000")
					this.fileAttachments = res.data.workOrderMediaVos.filter(item => item.mediaType === "1009")
					// this.demark(res.data);
					this.checkImages(res.data.workOrderMediaVos)
					// if (res.data.workOrderStatusId - 0 > 13) {
					// 	this.getDevice();
					// }
				})
			},
			// system/orderTemp/list
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "1005":
							this.fileList1.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						case "12":
							this.enginnerWriteImages.fileUrls[0] = dataElement.fileUrl || null;
							this.enginnerWriteImagesFileUrl = dataElement.fileUrl || null;
							break;
						case "13":
							this.userWriteImages.fileUrls[0] = dataElement.fileUrl || null;
							this.userWriteImagesFileUrl = dataElement.fileUrl || null;
							break;
						case "14":
							this.fileList3.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						case "15":
							this.fileList4.push({
								type: "image",
								url: dataElement.fileUrl,
								status: "success",
								name: "",
								message: "",
								thumb: "",
								size: 60489
							});
							break;
						default:
							continue;
					}
				}
			},
			// 流程
			demark(data) {
				this.historyList.push({
					id: 0,
					descTime: data.preArriveCustomerTime,
					title: '预计上门时间',
					istrue: !!data.preArriveCustomerTime && true
				}, {
					id: 1,
					descTime: data.pickOrderTime,
					title: '接单时间',
					istrue: !!data.pickOrderTime && true
				}, {
					id: 2,
					descTime: data.arriveCustomerTime,
					title: '上门时间',
					istrue: !!data.arriveCustomerTime && true
				}, {
					id: 3,
					descTime: data.startRecycleTime,
					title: '开始回收时间 ',
					istrue: !!data.startRecycleTime && true
				}, {
					id: 4,
					descTime: data.endRecycleTime,
					title: '结束回收时间',
					istrue: !!data.endRecycleTime && true
				})
			}
		},
		filters: {
			formatDate: function(value, args) {
				var dt = new Date(value);
				if (args == 'yyyy-M-d') { // yyyy-M-d
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					return `${year}-${month}-${date}`;
				} else if (args == 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					let hour = dt.getHours();
					let minute = dt.getMinutes();
					let second = dt.getSeconds();
					return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
				} else if (args == 'yyyy-MM-dd') { // yyyy-MM-dd
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${date}`;
				} else { // yyyy-MM-dd HH:mm:ss
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					let hour = dt.getHours().toString().padStart(2, '0');
					let minute = dt.getMinutes().toString().padStart(2, '0');
					let second = dt.getSeconds().toString().padStart(2, '0');
					return `${month}-${date} ${hour}:${minute}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			// box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);

			.main_body_view {
				margin: 10upx;
			}
			.title {
				// font-size: 20px;
				padding: 8px 0;
				margin-bottom: 12px;
				border-bottom: 1px solid rgba(0, 124, 233, 0.4);
			}
			.file {
				color: rgb(26, 115, 232);
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}

			.user_for {
				display: flex;
			}

			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}

			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}

			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}

			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;

			}
			// .sub {
			// 	display: flex;
			// 	justify-content: space-between;
			
			// 	button {
			// 		width: 240upx;
			// 		height: 60upx;
			// 	}
			// }
		}

		.write {
			display: flex;
			justify-content: space-around;

			.im {
				width: 300rpx;

				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>